﻿using System;
using System.Threading.Tasks;
using System.Threading;
using static System.Console;
using KongMing.Common;

namespace TaskUnitProject
{
    /// <summary>
    /// 1.创建Task任务的三种方式
    /// </summary>
    public class TaskUnit_1_1: UnitBase
    {

        public static void Go()
        {
            //Go1();
            //Go2();
            TaskDemo();
        }

        #region 不带参数和返回值的线程
        static void Go1()
        {
            Thread thread = new Thread(ThreadTest1);
            thread.Start();

            //1.new方式实例化一个Task，需要通过Start方法启动
            Task task1 = new Task(() =>
            {
                SleepSeconds(1);
                WriteCurrentTaskInfo("task1");
            });
            task1.Start();

            //2.Task.Factory.StartNew(Action action)创建和启动一个Task
            Task task2 = Task.Factory.StartNew(() =>
            {
                SleepSeconds(2);
                WriteCurrentTaskInfo("task2");
            });

            //3.Task.Run(Action action)将任务放在线程池队列，返回并启动一个Task
            Task task3 = Task.Run(() =>
            {
                SleepSeconds(3);
                WriteCurrentTaskInfo("task3");
            });

            WriteLine("执行主线程");
            ReadKey();
        }
        #endregion

        #region 带返回值的线程
        static void Go2()
        {
            Thread thread=new Thread(()=>ThreadTest2());
            thread.Start();
            //1.
            Task<string> task1=new Task<string>(() =>
            {
                SleepSeconds(1);
                return GetCurrentTaskInfo("task1");
            });
            task1.Start();
            //2.
            Task<string> task2 = Task.Factory.StartNew(() =>
            {
                SleepSeconds(2);
                return GetCurrentTaskInfo("task2");
            });
            //3.
            Task<string> task3 = Task.Run(() =>
            {
                SleepSeconds(3);
                return GetCurrentTaskInfo("task3");
            });
            WriteLine("执行主线程");
            WriteLine(task1.Result);
            WriteLine(task2.Result);
            WriteLine(task3.Result);
            
        }
        #endregion

        static void ThreadTest1()
        {
            SleepSeconds(1);
            WriteCurrentTaskInfo("Thread");
        }

        static string ThreadTest2()
        {
            SleepSeconds(1);
            return GetCurrentTaskInfo("Thread");
        }

        #region 测试
        public static void TaskDemo()
        {
            Task task=new Task(() =>
            {
                SleepSeconds(2);
                WriteLine("等待结束");
            });
            task.RunSynchronously();//将线程同步执行
            WriteLine("主线程结束");
        }
        #endregion
    }
}
